package com.example.truetimedemo

import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.truetimedemo.core.TimeSyncManager
import com.example.truetimedemo.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
import java.util.TimeZone

/**
 * TrueTime 的 demo 和进一步封装
 *
 * truetime-android 地址
 * https://github.com/instacart/truetime-android
 * https://github.com/LyyAndroids/truetime-android
 *
 * 一些ntp服务器的网址
 * https://dns.iui.im/ntp/
 */
class MainActivity : AppCompatActivity() {

    private val mBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(mBinding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        mBinding.btnGet.setOnClickListener {
            getInfo()
        }


    }

    private fun getInfo() {
//        val date = try {
//            App.trueTime.now()
//        }catch (e:Exception){
//            Log.e("young_test909090909","出现异常了，e=${e.message}")
//            App.trueTime.nowSafely()
//        }

        val date = TimeSyncManager.now()

        val strBuilder = StringBuilder()

        strBuilder.append("获取信息: \n")

        strBuilder.append("设备时间：${formatDate(Date())}\n")

        strBuilder.append("网络时间：${formatDate(date)}")

        mBinding.tvInfo.text = strBuilder.toString()
    }


    private fun formatDate(date: Date): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Instant.ofEpochMilli(date.time)
                .atZone(ZoneId.of("America/Los_Angeles"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        } else {
            val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            simpleDateFormat.timeZone = TimeZone.getTimeZone("America/Los_Angeles")
            simpleDateFormat.format(date)
        }
    }
}